package models;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/* For further MVC-fying: move these to a Controller class that accesses */
/* this class to set/get the static File: */
/* Variable "toSave" and its getters and setters */
/* Methods readFile(), readNewFile(), closeFile() and chooseFile() */
/* Can be merged with SemRepFileModel */

/* For now, this Model contains the ability to ask the user */
/* to choose a file that contains a lexicon. */
public class LexiconFileModel {
	
	private static boolean toSave;
	private static File file;
	
	public LexiconFileModel() {}
	
	public static void readFile() {
		if (file == null) {
			readNewFile();
		}
	}
	
	public static void readNewFile() {
		file = chooseFile();
	}
	
	public static void closeFile() {
		file = null;
	}
	
	private static File chooseFile() {
		File file = null;

		while (file == null) {
			JFileChooser fc = new JFileChooser("src/xml/languages");
			fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
			fc.setAcceptAllFileFilterUsed(false);
			FileNameExtensionFilter filter = new FileNameExtensionFilter("XML files (*.xml)", "xml");
			fc.setFileFilter(filter);
			
			int returnValue = (toSave ? fc.showSaveDialog(null) : fc.showOpenDialog(null));
			
			if (returnValue == JFileChooser.CANCEL_OPTION) {
				break;
			}
			
			String filePath = fc.getSelectedFile().getAbsolutePath();
			
			if ( filePath != null && !filePath.equals("") ) {
				if (!filePath.endsWith(".xml")) {
					filePath = filePath.concat(".xml");
				}
				file = new File(filePath);
			}
			
			if (file == null) {
				JOptionPane.showMessageDialog(null, "Please make sure the file name and extension is valid.", "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
		
		return file;
	}
	
	public static void setToSave(boolean newSave) {
		toSave = newSave;
	}
	
	public static boolean isToSave() {
		return toSave;
	}
	
	public static File getFile() {
		return file;
	}
	
	public static void setFile(File newFile) {
		file = newFile;
	}
}
